import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

// ReplaySubject
// 回放已经消失的事件。
/// 如果你想要缓存更多的数据，可以使用ReplaySubject，但是大多数情况下我们都用不到。
class ReplaySubjectDemoHome extends StatefulWidget {
  const ReplaySubjectDemoHome({Key? key}) : super(key: key);

  @override
  _ReplaySubjectDemoHomeState createState() => _ReplaySubjectDemoHomeState();
}

class _ReplaySubjectDemoHomeState extends State<ReplaySubjectDemoHome> {
  ReplaySubject<String> _replaySubject = ReplaySubject<String>();
  ReplaySubject<String> _replaySubject2 = ReplaySubject<String>(maxSize: 2);

  @override
  void initState() {
    super.initState();
    _replaySubject.add("1");
    _replaySubject.add("2");
    _replaySubject.add("3");

    _replaySubject.listen((event) => print("_replaySubject listener-1: $event"));
    _replaySubject.listen((event) => print("_replaySubject listener-2: $event"));
    _replaySubject.listen((event) => print("_replaySubject listener-3: $event"));

    _replaySubject2.add("1");
    _replaySubject2.add("2");
    _replaySubject2.add("3");

    _replaySubject2.listen((event) => print("_replaySubject2 listener-1: $event"));
    _replaySubject2.listen((event) => print("_replaySubject2 listener-2: $event"));
    _replaySubject2.listen((event) => print("_replaySubject2 listener-3: $event"));
  }

  @override
  void dispose() {
    _replaySubject.close();
    _replaySubject2.close();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ReplaySubjectDemo"),
      ),
      body: Center(
        child: Text("aaaaa"),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: Icon(Icons.add),
      ),
    );
  }
}

/*
I/flutter ( 1595): listener-1: 1
I/flutter ( 1595): listener-2: 1
I/flutter ( 1595): listener-3: 1
I/flutter ( 1595): listener-1: 2
I/flutter ( 1595): listener-2: 2
I/flutter ( 1595): listener-3: 2
I/flutter ( 1595): listener-1: 3
I/flutter ( 1595): listener-2: 3
I/flutter ( 1595): listener-3: 3

I/flutter ( 1595): _replaySubject2 listener-1: 2
I/flutter ( 1595): _replaySubject2 listener-2: 2
I/flutter ( 1595): _replaySubject2 listener-3: 2

I/flutter ( 1595): _replaySubject2 listener-1: 3
I/flutter ( 1595): _replaySubject2 listener-2: 3
I/flutter ( 1595): _replaySubject2 listener-3: 3

*/
